<?php
//CF_Controllers_Action
class AuthController extends CF_Controller_Action
{

	public function indexAction()
	{
		$this->view->title = "Authorisation";
		$form = new Application_Form_Login();
		$request = $this->getRequest();
		if ($request->isPost()) {
			if ($form->isValid($request->getPost())) {
				if ($this->_process($form->getValues())) {
					// We're authenticated! Redirect to the home page
					$this->_helper->redirector('index', 'index');
				}else{
					$this->view->authError = 'Invalid name or password';
					$form->populate($request->getPost());
				}
			}
		}
		$this->view->form = $form;
	}

	private function _process($values)
	{
		// Get our authentication adapter and check credentials
		$adapter = $this->_getAuthAdapter();
		$adapter->setIdentity($values['username']);
		$adapter->setCredential($values['password']);

		$auth = Zend_Auth::getInstance();
		$result = $auth->authenticate($adapter);
		if ($result->isValid()) {
			$user = $adapter->getResultRowObject();
			$auth->getStorage()->write($user);
			return true;
		}
		return false;
	}

	private function _getAuthAdapter()
	{
		//$dbAdapter = Zend_Db_Table::getDefaultAdapter();
		//$dbAdapter = Zend_Registry::get('dbAdapter');
		//Zend_Auth_Adapter_DbTable provides the ability to authenticate
		//against credentials stored in a database table
		//http://framework.zend.com/manual/en/zend.auth.adapter.dbtable.html
		//$authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);

//		$authAdapter->setTableName('users')
//		->setIdentityColumn('username')
//		->setCredentialColumn('password')
//		->setCredentialTreatment('SHA1(CONCAT(?,salt))');
		//Salting is a term referring to a technique which can highly improve
		//your application's security. It's based on the idea that concatenating
		//a random string to every password makes it impossible to accomplish a successful brute
		//force attack on the database using pre-computed hash values from a dictionary
		return Zend_Registry::get('authAdapter');
	}

	public function logoutAction()
	{
		Zend_Auth::getInstance()->clearIdentity();
		$this->_helper->redirector('index','auth'); // back to login page
	}



}



